<template>
  <div>
    <!-- 页面标题 -->
    <h1>部门管理</h1>

    <!-- 使用 el-row 布局，新增按钮在左，查询框在右 -->
    <el-row :gutter="20" align="middle" justify="space-between">
      <!-- 新增按钮区域 -->
      <el-col :span="6">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-col>

      <!-- 查询表单区域（只保留部门名） -->
      <el-col :span="8">
        <el-form class="demo-form-inline" @submit.prevent="handleSearch" style="display: flex; justify-content: flex-end;">
          <el-form-item label="部门名" label-width="70px">
            <el-input v-model="search.name" placeholder="请输入部门名" clearable style="width: 200px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" native-type="submit">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 数据表格展示部门信息 -->
    <el-table :data="tableData" style="width: 100%">
      <!-- ID 列 -->
      <el-table-column prop="id" label="ID" width="180" />

      <!-- 部门名称列 -->
      <el-table-column prop="name" label="部门名" width="180" />

      <!-- 创建时间列 -->
      <el-table-column label="创建时间" width="180">
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>

      <!-- 更新时间列 -->
      <el-table-column label="更新时间">
        <template #default="scope">
          {{ formatTime(scope.row.updateTime) }}
        </template>
      </el-table-column>

      <!-- 操作列：编辑和删除按钮 -->
      <el-table-column fixed="right" label="操作" width="100">
        <template #default="scope">
          <!-- 编辑按钮 -->
          <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <!-- 删除按钮 -->
          <el-button link type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗：新增/编辑 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
      <el-form :model="form" label-width="120px" ref="formRef">
        <el-form-item label="部门名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import dayjs from 'dayjs';
import {
  getDepartment,
  addDepartment,
  updateDepartment,
  deleteDepartment,
  indexDepartmentsById,
  getDepartmentWithParams
} from '../services/auth';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    // 表格数据
    const tableData = ref([]);

    // 搜索条件（仅保留 name）
    const search = ref({
      name: ''
    });

    // 弹窗相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const form = ref({
      id: null,
      name: '',
      remark: ''
    });
    let isEdit = false;

    // 时间格式化方法
    const formatTime = (time) => {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
    };

    // 获取部门列表
    const fetchData = async () => {
      try {
        const response = await getDepartment();
        if (response.data.code === 1) {
          tableData.value = response.data.data;
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error('获取部门数据失败:', error);
        ElMessage.error('获取部门数据失败');
      }
    };

    // 打开新增弹窗
    const handleAdd = () => {
      dialogTitle.value = '新增部门';
      isEdit = false;
      form.value = { name: '', remark: '' };
      dialogVisible.value = true;
    };

    // 打开编辑弹窗
    const handleEdit = async (row) => {
      try {
        const res = await indexDepartmentsById(row.id);
        if (res.data.code === 1) {
          form.value = res.data.data;
          dialogTitle.value = '编辑部门';
          isEdit = true;
          dialogVisible.value = true;
        } else {
          ElMessage.error(res.data.msg);
        }
      } catch (error) {
        console.error('获取部门详情失败:', error);
        ElMessage.error('获取部门详情失败');
      }
    };

    // 删除部门
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        await deleteDepartment(row.id);
        ElMessage.success('删除成功');
        fetchData(); // 刷新列表
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          ElMessage.error('删除失败');
        }
      }
    };

    // 提交新增或编辑
    const handleSubmit = async () => {
      try {
        if (isEdit) {
          await updateDepartment(form.value);
          ElMessage.success('更新成功');
        } else {
          await addDepartment(form.value);
          ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        fetchData(); // 刷新列表
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      }
    };

    // 查询功能
    const handleSearch = async () => {
      try {
        const params = {};
        if (search.value.name) params.name = search.value.name.trim();

        const response = await getDepartmentWithParams(params); // ✅ 使用服务端接口
        if (response.data.code === 1) {
          tableData.value = response.data.data;
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('查询失败');
      }
    };

    // 页面加载时自动获取数据
    onMounted(() => {
      fetchData();
    });

    return {
      tableData,
      search,
      dialogVisible,
      dialogTitle,
      form,
      formatTime,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSearch,
      handleSubmit
    };
  }
};
</script>

<style scoped>
.demo-form-inline {
  margin-top: 20px;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  display: flex;
  align-items: center;
}
</style>